import re
from datetime import datetime


def parse_aaii_investor_sentiment(text):
    """
    解析AAII投资者情绪调查数据，提取关键指标

    参数:
    text (str): 包含AAII投资者情绪调查数据的文本

    返回:
    dict: 包含解析后数据的字典
    """
    # 定义正则表达式模式
    weekly_data_pattern = re.compile(r'(\d{1,2}/\d{1,2}/\d{4})\s+([\d.]+%)\s+([\d.]+%)\s+([\d.]+%)')
    historical_avg_pattern = re.compile(r'Historical Averages\s+([\d.]+%)\s+([\d.]+%)\s+([\d.]+%)')
    bullish_high_pattern = re.compile(r'1-Year Bullish High:\s+([\d.]+%)\s+Week Ending (\d{1,2}/\d{1,2}/\d{4})')
    neutral_high_pattern = re.compile(r'1-Year Neutral High\s+([\d.]+%)\s+Week Ending (\d{1,2}/\d{1,2}/\d{4})')
    bearish_high_pattern = re.compile(r'1-Year Bearish High\s+([\d.]+%)\s+Week Ending (\d{1,2}/\d{1,2}/\d{4})')

    # 解析周度数据
    weekly_data = []
    for match in weekly_data_pattern.finditer(text):
        date_str, bullish, neutral, bearish = match.groups()
        weekly_data.append({
            'date': datetime.strptime(date_str, '%m/%d/%Y').strftime('%Y-%m-%d'),
            'bullish': float(bullish.rstrip('%')),
            'neutral': float(neutral.rstrip('%')),
            'bearish': float(bearish.rstrip('%'))
        })

    # 解析历史平均值
    historical_avg = {}
    match = historical_avg_pattern.search(text)
    if match:
        bullish, neutral, bearish = match.groups()
        historical_avg = {
            'bullish': float(bullish.rstrip('%')),
            'neutral': float(neutral.rstrip('%')),
            'bearish': float(bearish.rstrip('%'))
        }

    # 解析一年期最高值
    bullish_high = {}
    match = bullish_high_pattern.search(text)
    if match:
        value, date_str = match.groups()
        bullish_high = {
            'value': float(value.rstrip('%')),
            'date': datetime.strptime(date_str, '%m/%d/%Y').strftime('%Y-%m-%d')
        }

    neutral_high = {}
    match = neutral_high_pattern.search(text)
    if match:
        value, date_str = match.groups()
        neutral_high = {
            'value': float(value.rstrip('%')),
            'date': datetime.strptime(date_str, '%m/%d/%Y').strftime('%Y-%m-%d')
        }

    bearish_high = {}
    match = bearish_high_pattern.search(text)
    if match:
        value, date_str = match.groups()
        bearish_high = {
            'value': float(value.rstrip('%')),
            'date': datetime.strptime(date_str, '%m/%d/%Y').strftime('%Y-%m-%d')
        }

    # 构建结果字典
    result = {
        'weekly_data': weekly_data,
        'historical_averages': historical_avg,
        'bullish_high': bullish_high,
        'neutral_high': neutral_high,
        'bearish_high': bearish_high
    }

    return result


# 示例用法
if __name__ == "__main__":
    sample_text = """The AAII Investor Sentiment Survey
The AAII Sentiment Survey offers insight into the opinions of individual investors by asking them their thoughts on where the market is heading in the next six months and has been doing so since 1987. This market sentiment data is compiled and depicted below for individual use.
Investor sentiment is measured with a weekly survey conducted from Thursday at 12:01 a.m. until Wednesday at 11:59 p.m. Tracking sentiment gives investors a forward-looking perspective of the market instead of relying on historical data, which tends to result in hindsight bias.
AAII Members can login to vote in the AAII Investor Sentiment Survey today!
<---
Week Ending
Sentiment Votes
Bullish Neutral Bearish
7/9/2025
41.4%
23.0%
35.6%
7/2/2025
45.0%
21.9%
33.1%
6/25/2025
35.1%
24.7%
40.3%
6/18/2025
33.2%
25.4%
41.4%
Historical View
Historical Averages
37.5%
31.5%
31.0%
1-Year Bullish High:
52.7%
Week Ending 7/17/2024
1-Year Neutral High
34.0%
Week Ending 1/15/2025
1-Year Bearish High
61.9%
Week Ending 4/2/2025
"""
    parsed_data = parse_aaii_investor_sentiment(sample_text)

    # 打印解析结果
    import json

    print(json.dumps(parsed_data, indent=2))